using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using LinkPointTransaction;
using System.Collections.Specialized;
using System.Configuration;
using SiteManager;
using System.Text;
using System.Data.SqlClient;

/// <summary>
///    The page is designed and  developed to implement the functionality of Doctor's group
///    discount practice it allow Group Subscription of Doctors as featured doctors and process the YourPay Payment gateway
///    Author: Deepak 
///    Date: 3 Jan 2008
/// </summary>
public partial class Doctor_DoctorGroupPractice : System.Web.UI.Page
{
    /// <summary>
    /// Create object of manager and doctor Class Respectively
    /// </summary>
    Manager ObjManager = new Manager(true,"ConnectionString");
  //  Doctor ObjDoctor = new Doctor();
    localFunction drchk = new localFunction();

    static int count;
    static int DocCount;
    static Hashtable docData = new Hashtable();
    static Hashtable SubscribedDocData = new Hashtable();


    #region Variable Declaration
    /// <summary>
    /// Declare Variables
    /// </summary>
    protected string configfile;
    protected string keyfile;
    protected string host;
    protected int port;
    protected LinkPointTxn LPTxn;
    protected bool fLog = false;
    protected int logLvl = 0;
    protected string logFile = "";
    protected string baddrnum = "";
    protected string bzip = "";
    //protected string bCity = "";
    //protected string bState = "";
    protected string Name = "";
    protected string Email = "";
    protected string cardnumber = "";
    protected string expmonth = "";
    protected string expyear = "05";
    protected string total = "";
    //string strDate = "";
    protected string startdate = "";
    protected string periodicity = "";
    protected string installments = "";
    protected string pbthreshold = "";
   // int iDoctorid = 0;
   // string SpecialityName = "";
    string errorMessage = String.Empty;
    string filename = String.Empty;
    #endregion

    #region YourPay Process Variable Declaration
    /// <summary>
    /// Declare Variables Used In YourPay Process
    /// </summary>
    protected string order;
    protected string resp;
    protected bool fIE5;
    protected string R_Time;
    protected string R_Ref;
    protected string R_Approved;
    protected string R_Code;
    protected string R_Authresr;
    protected string R_Error;
    protected string R_OrderNum;
    protected string R_Message;
    protected string R_Score;
    protected string R_TDate;
    protected string R_AVS;
    protected string R_FraudCode;
    protected string R_ESD;
    protected string R_Tax;
    protected string R_Shipping;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        //Check Doctor Login
        drchk.checkDoctorLogin(true);

        //if (!CheckDoctorExist())
        //{
        //    WizardSubscription.Visible = false;
        //    lblMessage.Text = "You are already registered.";
        //}

        txtcardnumber.Attributes.Add("onkeypress", "return CheckCardNo(event)");

        if (!IsPostBack)
        {
            Session["SubscribedDoctors"] = "";
            
            Session["DocCount"] = "";
            DocCount = 0;
            docData.Clear();
            count = 0;

            MultiView1.SetActiveView(viewGetTotalDocs);
            ddlSubSpeciality.Enabled = false;
            ddlFeaturedDocType.Attributes.Add("onchange", "checkSelectedValue();");
            ltbnViewOne.Attributes.Add("onclick", "return checkDocCount();");
            lbtnDocDetails.Attributes.Add("onclick", "return checkId();");
                       
            //if (Session["userID"].ToString() != "" && Session["userID"] != null)
            //{
            //    iDoctorid = Convert.ToInt32(Session["userID"]);
            //}
            LoadCommonControls(); // Bind Dropdowns and radio button
            YearDisplay();
            MonthDisplay();
        }
    }

    #region Load Page Controls
    /// <summary>
    /// Bind Speciality/SubSpeciality/Subscription Level Dropdowns
    /// </summary>
    private void LoadCommonControls()
    {
        ObjManager.BindList("select id,name from tbl_speciality order by name", "name", "id", ddlSpeciality, "");
        ObjManager.BindList("select id,name from tbl_primaryspeciality union select id, name from tbl_Secondaryspeciality order  by name", "name", "id", ddlSubSpeciality, "Select");
        ObjManager.BindList("select FeatureDocTypeId,FeatureDocType from  tbl_FeatureDocType", "FeatureDocType", "FeatureDocTypeId", ddlFeaturedDocType, "");
        // ObjManager.BindList("select s.id,s.name from tbl_doctors doc,tbl_SecondarySpeciality  s where s.id=doc.SecondarySpecialityid", "name", "id", ddlSecSpeciality, "");
        ddlFeaturedDocType.Items.Insert(0, new ListItem("Select", "0"));
        //rbSubscription.Items.Add(new ListItem("Daily", "1"));
        rbSubscription.Items.Add(new ListItem("Monthly", "2"));
        rbSubscription.Items[0].Selected = true;
        rbSubscription.Items.Add(new ListItem("Annual", "3"));
    }

    private void YearDisplay()
    {
        ddlYear.Items.Insert(0, "Year");
        for (int i = 2007; i < 2013; i++)
        {
            ddlYear.Items.Add(i.ToString());
        }
    }

    private void MonthDisplay()
    {
        DataTable tbMonth = new DataTable();
        tbMonth.Columns.Add(new DataColumn("MonthNo"));
        tbMonth.Columns.Add(new DataColumn("MonthName"));
        tbMonth.Rows.Add(new object[] { "01", "Jan" });
        tbMonth.Rows.Add(new object[] { "02", "Feb" });
        tbMonth.Rows.Add(new object[] { "03", "Mar" });
        tbMonth.Rows.Add(new object[] { "04", "Apr" });
        tbMonth.Rows.Add(new object[] { "05", "May" });
        tbMonth.Rows.Add(new object[] { "06", "Jun" });
        tbMonth.Rows.Add(new object[] { "07", "July" });
        tbMonth.Rows.Add(new object[] { "08", "Aug" });
        tbMonth.Rows.Add(new object[] { "09", "Sep" });
        tbMonth.Rows.Add(new object[] { "10", "Oct" });
        tbMonth.Rows.Add(new object[] { "11", "Nov" });
        tbMonth.Rows.Add(new object[] { "12", "Dec" });
        ddlMonth.DataSource = tbMonth;
        ddlMonth.DataValueField = "MonthNo";
        ddlMonth.DataTextField = "MonthName";
        ddlMonth.DataBind();
        ddlMonth.Items.Insert(0, "Month");
    }
    #endregion

    #region Pre YourPay Process Function

    protected void ltbnViewOne_Click(object sender, EventArgs e)
    {
        if ((txtDocCount.Text.Trim()) != "")
        {
            DocCount = Convert.ToInt32(txtDocCount.Text);
        }
        MultiView1.SetActiveView(viewGetPremiumDetails);
        lblErrorMessage.Text = "Enter details for Doctor " + (count + 1);
        lblErrorMessage.Visible = true;
        lblErrorMessage.Font.Bold = true;
        lblErrorMessage.ForeColor = System.Drawing.Color.Red;
        if (ddlFeaturedDocType.SelectedIndex != 3)
        {
            fupl_photo.Enabled = false;
            txtdoctorStatement.Enabled = false;
            txtWebSite.Enabled = false;
        }
//        count = count + 1;
    }


    /// <summary>
    /// Process And Iterate Through Step 2 (Doctor's Email and Details Acceptance Step) To Save Infrmation About Doctor In HashTable
    /// </summary>
    protected void lbtnDocDetails_Click(object sender, EventArgs e)
    {
        // WORKING CODE
        // if (count == (Convert.ToInt32(Session["DocCount"].ToString()) - 1))
        //{
        //    if (DocDetails(count + 1))
        //    {
        //        MultiView1.SetActiveView(viewPayments); 
        //    }
        //    else
        //    {
        //        lblErrorMessage.Text = "Doctor Id Does not exist, Enter details for Doctor " + (count + 1);
        //        lblErrorMessage.Visible = true;
        //        lblErrorMessage.Font.Bold = true;
        //    }

        ////   //
        //}
        //else
        //{
        //    if (DocDetails(count + 1))
        //    {
        //        count = count + 1; 
        //        lblErrorMessage.Text = "Enter details for Doctor " + (count + 1);
        //        lblErrorMessage.Visible = true;
        //        lblErrorMessage.Font.Bold = true;
        //        txtDocEmail.Text = "";
        //    }
        //   else
        //    {
        //        lblErrorMessage.Text = "Doctor Id Does not exist, Enter details for Doctor " + (count + 1);
        //        lblErrorMessage.Visible = true;
        //        lblErrorMessage.Font.Bold = true;
        //    }
        //}
        // WORKING CODE
        
        if (count == (DocCount - 1))
        {
            if (DocDetails(count + 1))
            {
                if (DocCount == 2)
                {
                    if (rbSubscription.Text == "2")//Monthly
                    {
                        if (ddlFeaturedDocType.Text == "1")//Standard Featured Doctor
                        {
                            txttotal.Text = "94";
                        }
                        if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Doctor
                        {
                            txttotal.Text = "192";
                        }
                        if (ddlFeaturedDocType.Text == "3")//Premium Featured Doctor
                        {
                            txttotal.Text = "384";
                        }
                    }
                    else if (rbSubscription.Text == "3")
                    {
                        if (ddlFeaturedDocType.Text == "1")
                        {
                            txttotal.Text = "940";
                        }
                        if (ddlFeaturedDocType.Text == "2")
                        {
                            txttotal.Text = "1920";
                        }
                        if (ddlFeaturedDocType.Text == "3")
                        {
                            txttotal.Text = "3840";
                        }
                    }
                }
                else if (DocCount == 3)
                {
                    if (rbSubscription.Text == "2")//Monthly
                    {
                        if (ddlFeaturedDocType.Text == "1")//Standard Featured Doctor
                        {
                            txttotal.Text = "135";
                        }
                        if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Doctor
                        {
                            txttotal.Text = "276";
                        }
                        if (ddlFeaturedDocType.Text == "3")//Premium Featured Doctor
                        {
                            txttotal.Text = "552";
                        }
                    }
                    else if (rbSubscription.Text == "3")
                    {
                        if (ddlFeaturedDocType.Text == "1")
                        {
                            txttotal.Text = "1350";
                        }
                        if (ddlFeaturedDocType.Text == "2")
                        {
                            txttotal.Text = "2760";
                        }
                        if (ddlFeaturedDocType.Text == "3")
                        {
                            txttotal.Text = "5520";
                        }
                    }
                }
                else if (DocCount == 4)
                {
                    if (rbSubscription.Text == "2")//Monthly
                    {
                        if (ddlFeaturedDocType.Text == "1")//Standard Featured Doctor
                        {
                            txttotal.Text = "172";
                        }
                        if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Doctor
                        {
                            txttotal.Text = "352";
                        }
                        if (ddlFeaturedDocType.Text == "3")//Premium Featured Doctor
                        {
                            txttotal.Text = "704";
                        }
                    }
                    else if (rbSubscription.Text == "3")
                    {
                        if (ddlFeaturedDocType.Text == "1")
                        {
                            txttotal.Text = "1720";
                        }
                        if (ddlFeaturedDocType.Text == "2")
                        {
                            txttotal.Text = "3520";
                        }
                        if (ddlFeaturedDocType.Text == "3")
                        {
                            txttotal.Text = "7040";
                        }
                    }
                }
                else if (DocCount == 5)
                {
                    if (rbSubscription.Text == "2")//Monthly
                    {
                        if (ddlFeaturedDocType.Text == "1")//Standard Featured Doctor
                        {
                            txttotal.Text = "205";
                        }
                        if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Doctor
                        {
                            txttotal.Text = "420";
                        }
                        if (ddlFeaturedDocType.Text == "3")//Premium Featured Doctor
                        {
                            txttotal.Text = "840";
                        }
                    }
                    else if (rbSubscription.Text == "3")
                    {
                        if (ddlFeaturedDocType.Text == "1")
                        {
                            txttotal.Text = "2050";
                        }
                        if (ddlFeaturedDocType.Text == "2")
                        {
                            txttotal.Text = "4200";
                        }
                        if (ddlFeaturedDocType.Text == "3")
                        {
                            txttotal.Text = "8400";
                        }
                    }
                }
                else if (DocCount > 5)
                {
                    if (rbSubscription.Text == "2")//Monthly
                    {
                        if (ddlFeaturedDocType.Text == "1")//Standard Featured Doctor
                        {
                            txttotal.Text = Convert.ToString(40 * Convert.ToInt32(DocCount));
                        }
                        if (ddlFeaturedDocType.Text == "2")//Enhanced Featured Doctor
                        {
                            txttotal.Text = Convert.ToString(80 * Convert.ToInt32(DocCount));
                        }
                        if (ddlFeaturedDocType.Text == "3")//Premium Featured Doctor
                        {
                            txttotal.Text = Convert.ToString(160 * Convert.ToInt32(DocCount));
                        }
                    }
                    else if (rbSubscription.Text == "3")
                    {
                        if (ddlFeaturedDocType.Text == "1")
                        {
                            txttotal.Text = Convert.ToString(400 * Convert.ToInt32(DocCount));
                        }
                        if (ddlFeaturedDocType.Text == "2")
                        {
                            txttotal.Text = Convert.ToString(800 * Convert.ToInt32(DocCount));
                        }
                        if (ddlFeaturedDocType.Text == "3")
                        {
                            txttotal.Text = Convert.ToString(1600 * Convert.ToInt32(DocCount));
                        }
                    }
                }
                showDoctorDetails();
                MultiView1.SetActiveView(viewDocDetails);
            }
            else
            {
                lblErrorMessage.Text = "Doctor is already featured or is not registerd, Enter details for Doctor " + (count + 1);
                lblErrorMessage.Visible = true;
                lblErrorMessage.Font.Bold = true;
                lblErrorMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
        else
        {
            if (DocDetails(count + 1))
            {
                count = count + 1;
                lblErrorMessage.Text = "Enter details for Doctor " + (count + 1);
                lblErrorMessage.Visible = true;
                lblErrorMessage.Font.Bold = true;
                lblErrorMessage.ForeColor = System.Drawing.Color.Red;
                txtDocEmail.Text = "";
                txtdoctorStatement.Text = "";
                txtWebSite.Text = "";
            }
            else
            {
                lblErrorMessage.Text = "Doctor is already featured or is not registerd, Enter details for Doctor " + (count + 1);
                lblErrorMessage.Visible = true;
                lblErrorMessage.Font.Bold = true;
                lblErrorMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
    }


    /// <summary>
    /// Call Yourpay Functions And Process The Payment
    /// </summary>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int i;
        //IDictionaryEnumerator en = docData.GetEnumerator();
        //while (en.MoveNext())
        //{
        //    string str = en.Value.ToString();
        //} 

        SubscribedDocData.Clear();

        for (i = 1; i <= DocCount; i++)
        {
            SaveDataAfterApproval(i);
            //Response.Write(docData["drId" + i].ToString() + "<BR>");
            //Response.Write(docData["DocPhoto" + i].ToString() + "<BR>");
            //Response.Write(docData["DocEmail" + i].ToString() + "<BR>");
            //Response.Write(docData["DocStatement" + i].ToString() + "<BR>");
            //Response.Write(docData["DocWebsite" + i].ToString() + "<BR>");
            //Response.Write("iD: " + Session["DocId" + i] + " Photo: " + Session["DocPhoto" + i] + " Email: " + Session["DocEmail" + i] + " Statement: " + Session["DocStatement" + i] + " Website: " + Session["DocWebsite" + i]);
        }
//        Response.Write("On DoctorGroupPractice Page: " + SubscribedDocData.Count);
        Session["SubscribedDoctors"] = SubscribedDocData;
   
        //Parse form data
        ParseFormData();
        // process order
        ProcessOrder();

        //Status Page
        // Put user code to initialize the page here

        HttpBrowserCapabilities bc = Request.Browser;
        fIE5 = (bc.Browser == "IE" && bc.MajorVersion > 4);

        order = (string)Session["outXml"];
        resp = (string)Session["resp"];
        ParseResponse(resp);
 //       Response.Write("R_Approved: " + R_Approved);
        if (R_Approved == "APPROVED")
        {
        //for (i = 1; i <= DocCount; i++)
        //{
        //    SaveDataAfterApproval(i); 
        //    //Response.Write(docData["drId" + i].ToString() + "<BR>");
        //    //Response.Write(docData["DocPhoto" + i].ToString() + "<BR>");
        //    //Response.Write(docData["DocEmail" + i].ToString() + "<BR>");
        //    //Response.Write(docData["DocStatement" + i].ToString() + "<BR>");
        //    //Response.Write(docData["DocWebsite" + i].ToString() + "<BR>");
        //    //Response.Write("iD: " + Session["DocId" + i] + " Photo: " + Session["DocPhoto" + i] + " Email: " + Session["DocEmail" + i] + " Statement: " + Session["DocStatement" + i] + " Website: " + Session["DocWebsite" + i]);
        //}

        //Session["SubscribedDoctors"] = SubscribedDocData;
        
        //    // code for set IsActive false
        //    ObjManager.ExecuteQuery("update coupons set IsActive='false',UsedAsOn=getdate() where couponcode='" + txtCouponCode.Text.ToString() + "' and Fordoctorid='" + iDoctorid + "'");
        //    //end code
        }
    }

    /// <summary>
    /// DocDetails function get the doctor Id from tbl_doctors and add doctors info (user input) to hashtable
    /// </summary>
    protected bool DocDetails(int DocCount)
    {
        SqlDataReader sqlDr = ObjManager.ExecuteQuery("select id from tbl_doctors where email='" + txtDocEmail.Text + "' and (featuredoctypeId is null or featuredoctypeId < 1)");
        // WORKING CODE
        //if (sqlDr.Read())
        //{
        //    Session["DocId" + DocCount] = sqlDr["id"].ToString();
        //    sqlDr.Close();

        //    Session["DocPhoto" + DocCount] = "";
        //    // upload the doctor's image
        //    if (fupl_photo.HasFile)
        //    {
        //        errorMessage = ObjManager.UpLoadFile(fupl_photo, Server.MapPath("../images/Dr_images/"), ".jpg|.bmp|.gif|.jpeg", 512000);
        //        if (errorMessage.Length > 0)
        //        {
        //            lblErrorMessage.Text = errorMessage;
        //        //    e.Cancel = true;
        //        }
        //        else
        //            filename = fupl_photo.FileName;
        //        if (filename.Length > 0)
        //        {
        //            Session["DocPhoto" + DocCount] = filename;
        //        }
        //    }

        //    Session["DocEmail" + DocCount] = txtDocEmail.Text.ToString();
        //    Session["DocStatement" + DocCount] = txtdoctorStatement.Text.ToString();
        //    Session["DocWebsite" + DocCount] = txtWebSite.Text.ToString();
        //    return true;
        //}
        //else
        //{
        //    sqlDr.Close();
        //    return false;
        //} 
        // WORKING CODE

        if (sqlDr.Read())
        {
            try
            {
                docData.Add("drId" + DocCount, sqlDr["id"].ToString());
                sqlDr.Close();

                docData.Add("DocPhoto" + DocCount, "");
                docData.Add("DocIMG" + DocCount, "");
                docData.Add("DocIMG_th" + DocCount, "");

                Session["" + DocCount] = "";
                // upload the doctor's image
                if (fupl_photo.HasFile)
                {
                //    errorMessage = ObjManager.UpLoadFile(fupl_photo, Server.MapPath("../images/Dr_images/"), ".jpg|.bmp|.gif|.jpeg", 512000);
                //    if (errorMessage.Length > 0)
                //    {
                //        lblErrorMessage.Text = errorMessage;
                        //    e.Cancel = true;
                //    }
                //    else
                        filename = fupl_photo.FileName;
                    if (filename.Length > 0)
                    {
                        byte[] docimage;
                        HttpPostedFile Image;
                        
                        docimage = new byte[fupl_photo.PostedFile.ContentLength];
                        Image = fupl_photo.PostedFile;
                        Image.InputStream.Read(docimage, 0, (int)fupl_photo.PostedFile.ContentLength);

                        docData.Remove("DocPhoto" + DocCount);
                        docData.Remove("DocIMG" + DocCount);
                        docData.Remove("DocIMG_th" + DocCount);

                        docData.Add("DocPhoto" + DocCount, filename);
                        docData.Add("DocIMG" + DocCount, docimage);

                        localFunction th = new localFunction();
                        docData.Add("DocIMG_th" + DocCount, th.getThumbnaleImage(docimage, 80, 100));
                    }
                }

                docData.Add("DocEmail" + DocCount, txtDocEmail.Text.ToString());
                docData.Add("DocStatement" + DocCount, txtdoctorStatement.Text.ToString());
                docData.Add("DocWebsite" + DocCount, txtWebSite.Text.ToString());
            }
            catch
            {
                Response.Redirect("doctorGroupPractice.aspx"); // Case if user hit the back button and page is refreshed
            }
            return true;
        }
        else
        {
            sqlDr.Close();
            return false;
        }
    }

    /// <summary>
    /// Display Step 4 To User For Payment
    /// </summary>
    protected void btnconfirmDetails_Click(object sender, EventArgs e)
    {
        MultiView1.SetActiveView(viewPayments);
    }

    /// <summary>
    /// showDoctorDetails function fetch doctor's details and display it to user before payment confirmation
    /// </summary>
    protected void showDoctorDetails()
    {
        string ids;
        ids = "";
        for (int i = 1; i <= DocCount; i++)
        {
            if (i == 1)
            {
                ids = docData["drId" + i].ToString();
            }
            else
            {
                ids = ids + "," + docData["drId" + i].ToString();
            }
        }
        SqlDataReader sqlDr = ObjManager.ExecuteQuery("select id, email, address1, fname from tbl_doctors where id IN (" + ids + ")");
        rptDocDetails.DataSource = sqlDr;
        rptDocDetails.DataBind();
        sqlDr.Close();
    }

    protected void rptDocDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

    }

    #endregion

    #region YourPay Process Function
    /// <summary>
    /// Function Used In YourPay Process
    /// </summary>
    protected void ParseFormData()
    {
        bzip = ""; // txtbzip.Text;
        //bState = txtState.Text.Trim().ToString();
        //bCity = txtCity.Text.Trim().ToString();
        baddrnum = ""; // txtbaddrnum.Text;
        cardnumber = txtcardnumber.Text;
        expmonth = ddlMonth.SelectedValue.ToString();
        string r = ddlYear.SelectedValue.ToString();
        r = r.Substring(2);
        expyear = r;
        total = txttotal.Text;
        Name = ""; // txtName.Text;
        Email = ""; // txtEmail.Text;
        if ((total == null) || total.Length < 1) { total = "0.0"; }
        pbthreshold = "3";
        //strDate = System.DateTime.Now.ToShortDateString();
        //startdate = DateTime.Parse(strDate).ToString("yyyyMMdd");
        startdate = "immediate";
        periodicity = rbSubscription.SelectedItem.ToString();
        installments = "99";
        GetConfigParams();
    }

    private void GetConfigParams()
    {
        // get some stuff from app config
        //  NameValueCollection config1 = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/client");  commented at 131008 to fix
        NameValueCollection config1 = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/client");


        configfile = config1["Configfile"];
        keyfile = config1["Keyfile"];
        host = config1["Host"];
        port = Int32.Parse(config1["Port"]);

        //NameValueCollection config = (NameValueCollection)ConfigurationSettings.GetConfig("LPAPP_Config/opts"); commented at 131008 to fix
        NameValueCollection config = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("LPAPP_Config/opts");

        try
        {
            fLog = bool.Parse(config["fLog"]);
        }
        catch (Exception) { }

        try
        {
            logLvl = Int32.Parse(config["logLvl"]);
        }
        catch (Exception) { }

        try
        {
            logFile = config["logFile"];
        }
        catch (Exception) { }
    }

    private void ProcessOrder()
    {
        // create order            
        LPOrderPart order = LPOrderFactory.createOrderPart("order");
        // create a part we will use to build the order
        LPOrderPart op = LPOrderFactory.createOrderPart();

        // Build 'orderoptions'
        op.put("ordertype", "SALE");
        // add 'orderoptions to order
        order.addPart("orderoptions", op);

        // Build 'merchantinfo'
        op.clear();
        op.put("configfile", configfile);
        // add 'merchantinfo to order
        order.addPart("merchantinfo", op);

        // Build 'billing'
        // Required for AVS. If not provided, 
        // transactions will downgrade.
        op.clear();
        op.put("zip", bzip);
        //op.put("City", bCity);
        //op.put("State", bState);
        op.put("addrnum", baddrnum);
        // add 'billing to order
        order.addPart("billing", op);

        // Build 'creditcard'
        op.clear();
        op.put("cardnumber", cardnumber);
        op.put("cardexpmonth", expmonth);
        op.put("cardexpyear", expyear);
        // add 'creditcard to order
        order.addPart("creditcard", op);

        // Build 'payment'
        op.clear();
        op.put("chargetotal", total);
        // add 'payment to order
        order.addPart("payment", op);

        // build 'periodic' part
        op.clear();
        op.put("action", "SUBMIT");
        op.put("startdate", startdate);
        op.put("periodicity", periodicity);
        op.put("installments", installments);
        op.put("threshold", pbthreshold);
        // add 'periodic' to order
        order.addPart("periodic", op);

        // create transaction object	
        LPTxn = new LinkPointTxn();

        // get outgoing XML from the 'order' object
        string outXml = order.toXML();

        // Call LPTxn
        string resp = LPTxn.send(keyfile, host, port, outXml);

        //Store transaction data on Session and redirect
        Session["outXml"] = outXml;
        Session["resp"] = resp;

        Server.Transfer("DoctorGroupPracticestatus.aspx");
    }

    //Status Page
    protected void ParseResponse(string rsp)
    {
        R_Time = ParseTag("r_time", rsp);
        R_Ref = ParseTag("r_ref", rsp);
        R_Approved = ParseTag("r_approved", rsp);
        R_Code = ParseTag("r_code", rsp);
        R_Authresr = ParseTag("r_authresronse", rsp);
        R_Error = ParseTag("r_error", rsp);
        R_OrderNum = ParseTag("r_ordernum", rsp);
        R_Message = ParseTag("r_message", rsp);
        R_Score = ParseTag("r_score", rsp);
        R_TDate = ParseTag("r_tdate", rsp);
        R_AVS = ParseTag("r_avs", rsp);
        R_Tax = ParseTag("r_tax", rsp);
        R_Shipping = ParseTag("r_shipping", rsp);
        R_FraudCode = ParseTag("r_fraudCode", rsp);
        R_ESD = ParseTag("esd", rsp);
    }

    protected string ParseTag(string tag, string rsp)
    {
        StringBuilder sb = new StringBuilder(256);
        sb.AppendFormat("<{0}>", tag);
        int len = sb.Length;
        int idxSt = -1, idxEnd = -1;
        if (-1 == (idxSt = rsp.IndexOf(sb.ToString())))
        { return ""; }
        idxSt += len;
        sb.Remove(0, len);
        sb.AppendFormat("</{0}>", tag);
        if (-1 == (idxEnd = rsp.IndexOf(sb.ToString(), idxSt)))
        { return ""; }
        return rsp.Substring(idxSt, idxEnd - idxSt);
    }
    #endregion
    
    #region Post YourPay Process
    /// <summary>
    /// SaveDataAfterApproval function updates doctor's subscription level in tbl_doctors and add transaction details to 
    /// doctorSubscription table
    /// </summary>
    private void SaveDataAfterApproval(int docNum)
    {
        //Write Code to add the processed value in database

        Doctor ObjDoctor = new Doctor();

        ObjDoctor.DoctorId = Convert.ToInt32(docData["drId" + docNum].ToString());
      //  ObjDoctor.TransactionId = R_Ref;
        //ObjDoctor.TransactionDate = R_Time;//need to confirm  which date should be add ?? R_Time or startdate.
        ObjDoctor.TransactionAmount = txttotal.Text.ToString();
        //ObjDoctor.SubscriptionId = R_OrderNum;
        ObjDoctor.SubscriptionType = rbSubscription.SelectedItem.ToString();
        ObjDoctor.FeaturedocTypeId = Convert.ToInt32(ddlFeaturedDocType.Text);
        ObjDoctor.SpecialityId = Convert.ToInt32(ddlSpeciality.Text);

        ObjDoctor.SubSpecialityId = Convert.ToInt32(ddlSubSpeciality.Text);

        ObjDoctor.photo = docData["DocPhoto" + docNum].ToString();
        ObjDoctor.prof_desc = docData["DocStatement" + docNum].ToString();
        ObjDoctor.website = docData["DocWebsite" + docNum].ToString();

        if (docData["DocIMG" + docNum].ToString() != "")
        {
            ObjDoctor.image = (byte[])docData["DocIMG" + docNum];
            ObjDoctor.th_image = (byte[])docData["DocIMG_th" + docNum];
        }

 //       Response.Write("<br>" + ObjDoctor.DoctorId + "<BR>"); 
        
        SubscribedDocData.Add("Doc" + docNum, ObjDoctor);
        ObjDoctor = null;
//        ObjManager.ExecuteScalarQuery("update tbl_doctors set FeatureDocTypeId ='" + ObjDoctor.FeaturedocTypeId + "' where id ='" + ObjDoctor.DoctorId + "'");

//        ObjDoctor.InsertDoctorSubscription();
    }
    #endregion


}